#include "sht30_task.h"

#include "esp_log.h"

#define I2C_MASTER_SCL_IO GPIO_NUM_4
#define I2C_MASTER_SDA_IO GPIO_NUM_5
#define I2C_MASTER_NUM I2C_NUM_0
#define I2C_MASTER_FREQ_HZ 100000

static const char *TAG = "SHT30_TASK";

// 全局变量保存最新的温湿度数据
static float H;
static float T;
static bool sensor_initialized = false;
sht30_err_t sht30_err;

void sht30_task_entry(void *pvParameters) {
  /* 初始化SHT30 */
  sht30_config_t config = {.i2c_port = I2C_MASTER_NUM,
                           .dev_addr = SHT30_ADDR_DEFAULT,  // 0x44
                           .sda_gpio = I2C_MASTER_SDA_IO,
                           .scl_gpio = I2C_MASTER_SCL_IO,
                           .freq_hz = I2C_MASTER_FREQ_HZ};

  sht30_err = sht30_init(&config);
  if (sht30_err != SHT30_OK) {
    ESP_LOGE(TAG, "SHT30初始化失败: %d", sht30_err);
    sensor_initialized = false;
    // 即使初始化失败，也继续运行任务，尝试后续读取
  } else {
    sensor_initialized = true;
    ESP_LOGI(TAG, "SHT30初始化成功");
  }

  while (1) /* 循环任务 */
  {
    if (sensor_initialized) {
      sht30_err = sht30_read_data(&T, &H);
      if (sht30_err == SHT30_OK) {
        // ESP_LOGI(TAG, "H:%.2f%% T:%.2fC", H, T);
      } else {
        ESP_LOGE(TAG, "读取SHT30数据失败: %d", sht30_err);
      }
    } else {
      // 如果之前初始化失败，尝试重新初始化
      sht30_err = sht30_init(&config);
      if (sht30_err == SHT30_OK) {
        sensor_initialized = true;
        ESP_LOGI(TAG, "SHT30重新初始化成功");
      } else {
        ESP_LOGW(TAG, "SHT30重新初始化失败: %d", sht30_err);
      }
    }
    vTaskDelay(pdMS_TO_TICKS(1000));
  }
}

void get_HT(float *_H, float *_T) {
  *_H = H;
  *_T = T;
}

void create_sht30_task(void) {
  xTaskCreate(sht30_task_entry, "sht30_task", 4096, NULL, 10, NULL);
}